package cn.fzhui.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 授权servlet，用于检测登陆状态
 */
public class AuthServlet extends HttpServlet {

    /**
     * 没有登录，跳转到登陆
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        if (!this.checkLogin(req)) {
            HttpSession httpSession = req.getSession();
            httpSession.setAttribute("message", "请先登录！");
            // 没有登录跳转到登录页
            resp.sendRedirect("/login.jsp");
        } else {
            // 有登陆，继续后续操作
            super.service(req, resp);
        }
    }

    /**
     * 检查是否已经登陆
     */
    private boolean checkLogin(HttpServletRequest req) {
        HttpSession httpSession = req.getSession();

        if (httpSession.getAttribute("username") != null) {
            return true;
        }

        return false;
    }

}
